var app = getApp();
const utils = require('../../utils/util.js');
Page({
  data: {
    indicatorDots: true,
    vertical: false,
    autoplay: false,
    interval: 3000,
    duration: 1200,
    toView: 'blue',
    selectedMenuId: 0,
    total: {
      RealCount: 0,
      money: 0
    },
    loadingHidden: false, // loading
    swiperCurrent: 0,
    selectCurrent: 0,
    CurrentPage: 1,
    Categorys: [],
    goodsResult: [],
    banners: [],
    goodsf1: [],
    goodsf2: [],
    scrollTop: "0",
    Word: '', //关键词
    selCatId: 0,
    selCatName: '',
    Brands: [],
    selBrandId: 0,
    selBrandName: '',
    Prices: [],
    selPriceId: 0,
    selPriceName: '',
    isCategoryTap: false,
    isBrandTap: false,
    isPriceTap: false,
    showSearch: false,
    searchCategory: [], //当前搜索类型
    saveHidden: true,
    allSelect: true,
    noSelect: false,
    mallName: '',
    cartInfo: {},
    hasMoreSelect: false,
    selectSize: "",
    selectSizePrice: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 0,
    buyNumMin: 0,
    buyNumMax: 0,
    propertyChildIds: "",
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    favorite: false,
    CurrentPid: 0,
    counts: 0,
    categories: [],
    pids: "",
    add: 0,
    realcounts: "",
    animationData: "",
    showModalStatus: false,
    skuTitles: [],
    attrvalue: "",
    addNumber: false,
    skuArr: [],
    skugid: '',
    SKUCount: 0,
    scrollTopId: "",
    selectProduct: [],
    allGoodsResult: [],
    countPrice: 0,
    // selectCount: 0,
    goodsDetail: {},
    skuProducts: {},
    loadingMoreHidden: true,
    isAccredit: false
  },
  //跳转详情
  toDetails: function(e) {
    let pid = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/goods-details/index?id=' + pid,
    })
  },
  //规格选择颜色变化
  selectAttr: function(e) {
    var that = this;
    var namearr = e.currentTarget.dataset.namearr
    var attrid = e.currentTarget.dataset.attrid
    var skulist = that.data.skuTitles
    var kid = 0 //颜色变化初始值
    for (var i = 0; i < skulist.length; i++) { //一级数组
      var nameArr = skulist[i].nameArr
      for (var j = 0; j < nameArr.length; j++) { //二级数组
        if (nameArr[j].IsInput == 1) {
          var nameAttrValue = nameArr[j].InputValue
        } else {
          var nameAttrValue = nameArr[j].attrvalue
        }
        if (nameAttrValue == namearr) {
          if (nameArr[j].kid == 0) {
            nameArr[j].kid = 1
          } else {
            nameArr[j].kid = 0
          }
        } else if (nameAttrValue != namearr && attrid == nameArr[j].AttrId) {
          nameArr[j].kid = 0
        } else if (attrid != nameArr[j].AttrId) {
          if (nameArr[j].kid != 1) {
            nameArr[j].kid = 3
            that.selectionPid(skulist, namearr, attrid)
          }
        }
      }
    }
    that.setData({
      skuTitles: skulist
    })
    var pidArr = []
    for (var p = 0; p < skulist.length; p++) { //选中对应kid筛选pid
      var nameArry = skulist[p].nameArr
      var arry = skulist[p].arr
      for (var h = 0; h < nameArry.length; h++) {
        if (nameArry[h].kid == 1) {
          if (nameArry[h].IsInput == 0) {
            var nameAttrValue = nameArry[h].attrvalue
          } else {
            var nameAttrValue = nameArry[h].InputValue
          }
          for (var m = 0; m < arry.length; m++) {
            if (arry[m].IsInput == 0) {
              var arrAttrValue = arry[m].AttrValue
            } else {
              var arrAttrValue = arry[m].InputValue
            }
            if (nameAttrValue == arrAttrValue) {
              pidArr.push(arry[m].Pid)
            }
          }
        }
      }
    }
    var nary = pidArr.sort();
    that.arrRepeat(nary, skulist.length) //一共几组sku skulist.length
  },
  //查找数组重复次数的组合pid
  arrRepeat: function(arr, skuCount) {
    var that = this;
    var pid = 0;
    var arrStr = JSON.stringify(arr),
      str;
    for (var i = 0; i < arr.length; i++) {
      if ((arrStr.match(new RegExp(arr[i], "g")).length) == skuCount) { //出现重复的次数等于sku组的出现次数
        that.setData({
          CurrentPid: arr[i] //最终的组合pid
        })
        pid = arr[i]
      }
    }
    if (pid != 0) {
      that.onProductSKU(pid)
      let total = that.data.total;
      total.RealCount = 0;
      that.setData({
        addNumber: false,
        total: total
      })
    }
  },
  //返回选中的pid
  selectionPid: function(skulist, text, attrid) {
    var that = this;
    for (var i = 0; i < skulist.length; i++) {
      if (attrid == skulist[i].AttrId) {
        var arr = skulist[i].arr
        for (var j = 0; j < arr.length; j++) {
          if (arr[j].IsInput == 0) {
            var arrAttrValue = arr[j].AttrValue
          } else {
            var arrAttrValue = arr[j].InputValue
          }
          if (text == arrAttrValue) {
            var Pid = arr[j].Pid
            that.otherPid(skulist, Pid, attrid)
          }
        }
      }
    }
  },
  //判断另一组可选择的规格值
  otherPid: function(skulist, pid, attrid) {
    var that = this;
    var valueArr = []
    for (var i = 0; i < skulist.length; i++) {
      if (attrid != skulist[i].AttrId) {
        var arr = skulist[i].arr
        var nameArr = skulist[i].nameArr
        for (var j = 0; j < arr.length; j++) {
          if (pid == arr[j].Pid) {
            if (arr[j].IsInput == 0) {
              var AttrValue = arr[j].AttrValue
            } else {
              var AttrValue = arr[j].InputValue
            }
            that.check2(valueArr, AttrValue)
            if (!that.check2(valueArr, AttrValue)) {
              valueArr.push(AttrValue)
              for (var f = 0; f < valueArr.length; f++) {
                for (var k = 0; k < nameArr.length; k++) {
                  if (nameArr[k].IsInput == 0) {
                    var nameArrValue = nameArr[k].attrvalue
                  } else {
                    var nameArrValue = nameArr[k].InputValue
                  }
                  if (valueArr[f] == nameArrValue && nameArr[k].kid != 1) {
                    nameArr[k].kid = 0
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  //数组去重
  check2: function(arr, text) {
    var state = false; //默认不存在
    if (arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        if (text == arr[i]) {
          state = true; //已经存在
          break;
        }
      }
    }
    return state;
  },
  //接口取值
  onProductSKU: function(pid) {
    console.log("onProductSKU")
    var that = this;
    let skuProducts = {};
    wx.request({
      url: app.globalData.host + '/api/Store/GetPartProductInfo',
      data: {
        pid: pid
      },
      success: function(res) {
        if (res.data.Code == 0) {

          skuProducts.Pid = res.data.Data.Pid;
          skuProducts.Name = res.data.Data.Name;
          skuProducts.ShopPrice = res.data.Data.ShopPrice;
          skuProducts.skuCount = 0;
          that.setData({
            skuProducts: skuProducts
          })
        }
      }
    })
    wx.request({
      url: app.globalData.host + '/api/store/Product',
      data: {
        pid: pid
      },
      success: function(res) {
        console.log(res);
        if (res.data.Code == 0) {
          skuProducts.StockNumber = res.data.Data.StockNumber
          that.setData({
            skuProducts: skuProducts
          })
        }
      }
    })
  },
  //重新push新数组
  ProductSKU: function(skuTitle, skuList) {
    var that = this;
    var skuTitles = skuTitle
    var skuList = skuList
    for (var i = 0; i < skuTitles.length; i++) {
      for (var j = 0; j < skuList.length; j++) {
        if (skuTitles[i].AttrId == skuList[j].AttrId) {
          var f = {}
          f.AttrId = skuList[j].AttrId
          f.AttrName = skuList[j].AttrName
          f.AttrValue = skuList[j].AttrValue
          f.Pid = skuList[j].Pid
          f.RecordId = skuList[j].RecordId
          f.IsInput = skuList[j].IsInput
          f.InputValue = skuList[j].InputValue
          f.sid = 0
          f.ShowImg = app.globalData.image800_800host + skuList[j].ShowImg
          skuTitles[i].arr.push(f)
          if (skuList[j].IsInput == 1) { //手动输入
            var skuValue = skuList[j].InputValue
          } else {
            var skuValue = skuList[j].AttrValue
          }
          if (!that.check(skuTitles[i].nameArr, skuValue)) {
            skuTitles[i].nameArr.push({
              attrvalue: skuList[j].AttrValue,
              kid: 0,
              AttrId: skuList[j].AttrId,
              IsInput: skuList[j].IsInput,
              InputValue: skuList[j].InputValue
            })
          }
        }
      }
    }
    that.setData({
      skuTitles: skuTitles
    })
  },
  //数组去重
  check: function(arr, text) {
    var state = false; //默认不存在
    if (arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        if (text == arr[i].attrvalue || text == arr[i].InputValue) {
          state = true; //已经存在
          break;
        }
      }
    }
    return state;
  },
  // 弹出层
  showModal: function(e) {
    // 显示遮罩层
    var pid = e.currentTarget.dataset.pid;
    this.productSearch(pid)
    var SKUGid = e.currentTarget.dataset.skugid;
    this.setData({
      skugid: SKUGid,
      addNumber: false,
      CurrentPid: 0,
      loadingMoreHidden: true
    })
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function() {
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function() {
    // 隐藏遮罩层
    let skuProducts = {};
    skuProducts.Pid = 0;
    skuProducts.Name = "";
    skuProducts.ShopPrice = 0;
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    this.setData({
      animationData: animation.export(),
      skuTitles: [],
      skuProducts: skuProducts
    })
    setTimeout(function() {
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

  productSearch: function(pid) {
    var that = this
    wx.request({
      url: app.globalData.host + '/api/store/GetProductSkuInfo',
      data: {
        pid: pid
      },
      success: function(res) {
        console.log(res)
        that.setData({
          loadingMoreHidden: false
        })
        var p = res.data.Data;
        var skuList = res.data.Data.ProductSKUList
        var skuTitle = res.data.Data.CurrProductSkuList
        for (var k = 0; k < skuTitle.length; k++) { //初始化二维数组
          skuTitle[k].arr = []
          skuTitle[k].nameArr = []
        }
        that.ProductSKU(skuTitle, skuList);
        let skuProductObj = {};
        let skuArr = that.data.skuArr;
        for (let i = 0; i < skuArr.length; i++) {
          if (pid == skuArr[i].Pid) {
            skuProductObj.pid = pid;
            skuProductObj.Name = skuArr[i].Name;
            skuProductObj.ShopPrice = skuArr[i].ShopPrice;
            break;
          }
        }
        that.setData({
          skuProducts: skuProductObj
        })
      }
    })
  },
  addShopCar: function() {
    var that = this;
    if (that.data.CurrentPid == 0 || that.data.CurrentPid == "") {
      wx.showModal({
        title: '提示',
        content: '请选择商品',
        showCancel: false
      })
      return;
    } else if (that.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '暂时缺货哦~',
        showCancel: false
      })
      return;
    } else {
      wx.request({
        url: app.globalData.host + '/api/cart/AddProduct',
        data: {
          uid: app.globalData.userInfo.Uid,
          pid: that.data.CurrentPid,
          buyCount: that.data.buyNumber
        },
        success: function(res) {
          if (res.data.Code == 0) {
            that.setData({
              shopNum: res.data.Data
            });
            wx.showToast({
              title: '加入购物车成功',
              icon: 'success',
              duration: 2000,
              success: function() {
                that.reqShop();
              }
            })
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.Message,
              showCancel: false
            })
          }
        }
      })
    }
  },


  delItem: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var cart = this.data.cartInfo;
    var t = e.currentTarget.dataset.type; //移动类型0：普通商品1：满减商品
    var list = cart.StoreCartList[0].CartProductList;
    if (t == 1) {
      var pindex = e.currentTarget.dataset.pindex;
      list = cart.StoreCartList[0].CartFullCutList[parseInt(pindex)].FullCutCartProductList;
    }
    var goods = list[parseInt(index)].OrderProductInfo;
    list[parseInt(index)].IsSelected = false;
    var selList = that.getSelList(cart);
    wx.request({
      url: app.globalData.host + '/api/cart/DelProduct',
      data: {
        pid: goods.Pid,
        uid: app.globalData.userInfo.Uid,
        selList: selList
      },
      success: function(res) {
        if (res.data.Code == 0) {
          var cart = that.processImageHost(res.data.Data);
          that.setData({
            cartInfo: cart
          });
          that.setGoodsList(that.getSaveHide(), that.allSelect(), that.noSelect());
        } else {
          wx.showToast({
            title: '系统错误',
            content: res.data.Message
          })
        }
      }
    })

  },
  selectTap: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var cart = this.data.cartInfo;
    var t = e.currentTarget.dataset.type; //移动类型0：普通商品1：满减商品
    var list = cart.StoreCartList[0].CartProductList;
    if (t == 1) {
      var pindex = e.currentTarget.dataset.pindex;
      list = cart.StoreCartList[0].CartFullCutList[parseInt(pindex)].FullCutCartProductList;
    }
    if (index !== "" && index != null) {
      list[parseInt(index)].IsSelected = !list[parseInt(index)].IsSelected;
      var selList = that.getSelList(cart);
      wx.request({
        url: app.globalData.host + '/api/cart/CancelOrSelectCartItem',
        data: {
          uid: app.globalData.userInfo.Uid,
          selList: selList
        },
        success: function(res) {
          if (res.data.Code == 0) {
            var cart = that.processImageHost(res.data.Data);
            that.setData({
              cartInfo: cart
            });
            that.setGoodsList(that.getSaveHide(), that.allSelect(), that.noSelect());
          } else {
            wx.showToast({
              title: '系统错误',
              content: res.data.Message
            })
          }
        }
      })
    }
  },

  allSelect: function() {
    if (this.data.cartInfo.StoreCartList.length == 0) {
      return false;
    }
    var list = this.data.cartInfo.StoreCartList[0].CartProductList;
    var cutList = this.data.cartInfo.StoreCartList[0].CartFullCutList;
    var allSelect = false;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.IsSelected) {
        allSelect = true;
      } else {
        allSelect = false;
        break;
      }
    }
    for (var i = 0; i < cutList.length; i++) {
      for (var j = 0; j < cutList[i].FullCutCartProductList.length; j++) {
        var curItem = cutList[i].FullCutCartProductList[j];
        if (curItem.IsSelected) {
          allSelect = true;
        } else {
          allSelect = false;
          break;
        }
      }
    }
    return allSelect;
  },
  noSelect: function() {
    if (this.data.cartInfo.StoreCartList.length == 0) {
      return false;
    }
    var list = this.data.cartInfo.StoreCartList[0].CartProductList;
    var cutList = this.data.cartInfo.StoreCartList[0].CartFullCutList;
    var noSelect = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (!curItem.IsSelected) {
        noSelect++;
      }
    }
    var c = 0;
    for (var i = 0; i < cutList.length; i++) {
      for (var j = 0; j < cutList[i].FullCutCartProductList.length; j++) {
        c++;
        var curItem = cutList[i].FullCutCartProductList[j];
        if (curItem.IsSelected) {
          noSelect++;
        }
      }
    }
    if (noSelect == (list.length + c)) {
      return true;
    } else {
      return false;
    }
  },
  setGoodsList: function(saveHidden, allSelect, noSelect) {
    this.setData({
      saveHidden: saveHidden,
      allSelect: allSelect,
      noSelect: noSelect
    });

  },
  bindAllSelect: function() {
    var that = this;
    var cart = this.data.cartInfo;
    var currentAllSelect = this.data.allSelect;
    var list = cart.StoreCartList[0].CartProductList;
    var cutList = cart.StoreCartList[0].CartFullCutList;
    if (currentAllSelect) {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i];
        curItem.IsSelected = false;
      }
      for (var i = 0; i < cutList.length; i++) {
        for (var j = 0; j < cutList[i].FullCutCartProductList.length; j++) {
          var curItem = cutList[i].FullCutCartProductList[j];
          curItem.IsSelected = false;
        }
      }
    } else {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i];
        curItem.IsSelected = true;
      }
      for (var i = 0; i < cutList.length; i++) {
        for (var j = 0; j < cutList[i].FullCutCartProductList.length; j++) {
          var curItem = cutList[i].FullCutCartProductList[j];
          curItem.IsSelected = true;
        }
      }
    }

    var selList = that.getSelList(cart);
    wx.request({
      url: app.globalData.host + '/api/cart/CancelOrSelectCartItem',
      data: {
        uid: app.globalData.userInfo.Uid,
        selList: selList
      },
      success: function(res) {
        if (res.data.Code == 0) {
          var cart = that.processImageHost(res.data.Data);

          that.setData({
            cartInfo: cart
          });
          that.setGoodsList(that.getSaveHide(), that.allSelect(), that.noSelect());
        } else {
          wx.showToast({
            title: '系统错误',
            content: res.data.Message
          })
        }
      }
    })
  },
  // numJiaTap: function (e) {//规格加
  //   var that = this;
  //   let skuProducts = that.data.skuProducts;
  //   console.log(skuProducts);
  //   if (skuProducts.Pid != 0) {
  //     var total = that.data.total;
  //     var pid = skuProducts.Pid;
  //     var selectProduct = that.data.selectProduct;
  //     var productInfo = that.data.goodsDetail.ProductInfo
  //     var productList = that.data.allGoodsResult
  //     total.RealCount += 1
  //     total.money.toFixed(2)
  //     total.money += skuProducts.ShopPrice
  //     total.money.toFixed(2)
  //     selectProduct.push({ pid: pid, count: 1, total: total, ShopPrice: skuProducts.ShopPrice, })
  //     var countPrice = 0
  //     for (var i = 0; i < selectProduct.length; i++) {
  //       countPrice = countPrice + selectProduct[i].ShopPrice
  //     }
  //     that.setData({
  //       'total': total,
  //       countPrice: countPrice.toFixed(2),
  //       addNumber: true,
  //       selectProduct: selectProduct
  //     });
  //     // wx.showToast({
  //     //   title: '加入成功',
  //     //   icon: 'success',
  //     //   duration: 2000
  //     // })
  //   } else {
  //     wx.showModal({
  //       title: '提示',
  //       content: '请选择商品',
  //       showCancel: false
  //     })
  //     return
  //   }
  // },

  numJiaTap: function(e) { //规格加
    var that = this;
    console.log(e)
    var pid = e.currentTarget.dataset.pid;
    let skuProducts = that.data.skuProducts;
    console.log(skuProducts);
    if (skuProducts.Pid != 0) {
      var total = that.data.total;
      var pid = skuProducts.Pid;
      var stockNumber = skuProducts.StockNumber;
      var selectProduct = that.data.selectProduct;
      var productInfo = that.data.goodsDetail.ProductInfo
      var productList = that.data.allGoodsResult
      console.log(productList);
      if (skuProducts.skuCount < stockNumber) {
        skuProducts.skuCount += 1
        total.RealCount += 1
        total.money.toFixed(2)
        total.money += skuProducts.ShopPrice
        total.money.toFixed(2)
      } else {
        wx.showModal({
          title: '提示',
          content: '商品库存不足或未选择商品规格',
          showCancel: false
        })
        return
      }
      selectProduct.push({
        pid: pid,
        count: 1,
        total: total,
        ShopPrice: skuProducts.ShopPrice,
      })
      var countPrice = 0
      for (var i = 0; i < selectProduct.length; i++) {
        countPrice = countPrice + selectProduct[i].ShopPrice
      }
      that.setData({
        'total': total,
        countPrice: countPrice.toFixed(2),
        addNumber: true,
        selectProduct: selectProduct
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '请选择商品',
        showCancel: false
      })
      return
    }
  },

  jiaBtnTap: function(e) {
    console.log("jiaBtnTap");
    var that = this;
    let back = '/pages/classes-list/index';
    let isAccredit = that.data.isAccredit;
    if (!isAccredit) {
      wx.showModal({
        title: '提示',
        content: '登陆后即可点餐，是否确认登陆？',
        success: function(res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../accredit/index?back=' + back,
            })
          }
        }
      })
      return;
    }
    var index = e.currentTarget.dataset.index;
    var pid = e.currentTarget.dataset.pid;
    var total = that.data.total;
    var selectProduct = that.data.selectProduct;
    var stockNumber = e.currentTarget.dataset.stocknumber;
    let shopPrice = e.currentTarget.dataset.shopprice;
    that.setData({
      pids: pid,
    })
    var productList = that.data.goodsResult;
    for (var j = 0; j < productList.length; j++) {//商品
      if (pid == productList[j].Pid) {
        if (productList[j].RealCount < stockNumber) {
          productList[j].RealCount += 1
          total.RealCount += 1
          total.money.toFixed(2)
          total.money += productList[j].ShopPrice
          total.money.toFixed(2)
        } else {
          wx.showModal({
            title: '提示',
            content: '商品库存不足',
            showCancel: false
          })
          return
        }
        break;
      }
    }
    selectProduct.push({ pid: pid, count: 1, ShopPrice: shopPrice, total: total })
    var countPrice = 0
    for (var i = 0; i < selectProduct.length; i++) {
      countPrice = countPrice + selectProduct[i].ShopPrice
    }
    that.setData({
      'goodsResult': productList,
      'total': total,
      countPrice: countPrice.toFixed(2),
      selectProduct: selectProduct
    });
  },
  numJianTap: function(e) { //规格减
    var that = this;
    if (that.data.total.RealCount > 0) {
      var total = that.data.total;
      var pid = that.data.CurrentPid;
      var selectProduct = that.data.selectProduct;
      total.RealCount -= 1
      total.money.toFixed(2)
      // total.money -= productList[j].ShopPrice
      total.money.toFixed(2)

      for (var i = 0; i < selectProduct.length; i++) {
        if (selectProduct[i].pid == pid) {
          selectProduct.splice(i, 1)
          break;
        }
      }
      var countPrice = 0
      for (var i = 0; i < selectProduct.length; i++) {
        countPrice = countPrice + selectProduct[i].ShopPrice
      }
      that.setData({
        'total': total,
        countPrice: countPrice.toFixed(2),
        selectProduct: selectProduct
      });
    } else {
      return
    }
  },

  jianBtnTap2: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var pidd = e.currentTarget.dataset.pid;
    var total = that.data.total;
    var selectProduct = that.data.selectProduct
    that.setData({
      pids: pidd
    })
    var productList = that.data.goodsResult
    for (var j = 0; j < productList.length; j++) { //商品
      if (pidd == productList[j].Pid) {
        if (productList[j].RealCount < 1) {
          return
        } else {
          productList[j].RealCount -= 1
          total.RealCount -= 1
          total.money.toFixed(2)
          total.money -= productList[j].ShopPrice
        }
        break;
      }
    }
    for (var i = 0; i < selectProduct.length; i++) {
      if (selectProduct[i].pid == pidd) {
        selectProduct.splice(i, 1)
        break;
      }
    }
    var countPrice = 0
    for (var i = 0; i < selectProduct.length; i++) {
      countPrice = countPrice + selectProduct[i].ShopPrice
    }
    that.setData({
      'goodsResult': productList,
      'total': total,
      countPrice: countPrice.toFixed(2),
      selectProduct: selectProduct
    });
  },
  editTap: function() {

    this.setGoodsList(!this.getSaveHide(), this.allSelect(), this.noSelect());
  },
  saveTap: function() {

    this.setGoodsList(!this.getSaveHide(), this.allSelect(), this.noSelect());
  },
  getSaveHide: function() {
    return this.data.saveHidden;
  },
  deleteSelected: function() {
    var that = this;
    var cart = this.data.cartInfo;
    var list = cart.StoreCartList[0].CartProductList;
    var cutList = cart.StoreCartList[0].CartFullCutList;
    var pids = '';
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.IsSelected) {
        pids += curItem.OrderProductInfo.Pid + ',';
        curItem.IsSelected = false;
      }
    }
    for (var i = 0; i < cutList.length; i++) {
      for (var j = 0; j < cutList[i].FullCutCartProductList.length; j++) {
        var curItem = cutList[i].FullCutCartProductList[j];
        if (curItem.IsSelected) {
          pids += curItem.OrderProductInfo.Pid + ',';
          curItem.IsSelected = false;
        }
      }
    }
    var selList = that.getSelList(cart);
    wx.request({
      url: app.globalData.host + '/api/cart/DelProducts',
      data: {
        pids: pids,
        uid: app.globalData.userInfo.Uid,
        selList: selList
      },
      success: function(res) {
        if (res.data.Code == 0) {
          var cart = that.processImageHost(res.data.Data);
          that.setData({
            cartInfo: cart
          });
          that.setGoodsList(that.getSaveHide(), that.allSelect(), that.noSelect());
        } else {
          wx.showToast({
            title: '系统错误',
            content: res.data.Message
          })
        }
      }
    })
    this.setGoodsList(this.getSaveHide(), this.allSelect(), this.noSelect());
  },
  getSelList: function(cart) {
    var selList = '';
    var list = cart.StoreCartList[0].CartProductList;
    var cutList = cart.StoreCartList[0].CartFullCutList;
    for (var i = 0; i < list.length; i++) {
      if (list[i].IsSelected) {
        selList += list[i].OrderProductInfo.Type + '_' + list[i].OrderProductInfo.Pid + ','
      }

    }
    for (var i = 0; i < cutList.length; i++) {
      for (var j = 0; j < cutList[i].FullCutCartProductList.length; j++) {
        var curItem = cutList[i].FullCutCartProductList[j];
        if (curItem.IsSelected) {
          selList += curItem.OrderProductInfo.Type + '_' + curItem.OrderProductInfo.Pid + ','
        }
      }
    }
    if (selList == '') {
      selList = '_'
    };
    return selList;
  },
  processImageHost: function(cart) {
    if (cart.StoreCartList.length > 0) {
      for (var i = 0; i < cart.StoreCartList[0].CartProductList.length; i++) {
        //主图
        cart.StoreCartList[0].CartProductList[i].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreCartList[0].CartProductList[i].OrderProductInfo.ShowImg;
        if (cart.StoreCartList[0].CartProductList[i].GiftList.length > 0) {
          for (var j = 0; j < cart.StoreCartList[0].CartProductList[i].GiftList.length; j++) {
            //赠品图片
            cart.StoreCartList[0].CartProductList[i].GiftList[j].ShowImg = app.globalData.image190_190host + cart.StoreCartList[0].CartProductList[i].GiftList[j].ShowImg;
          }
        }
      }
      for (var i = 0; i < cart.StoreCartList[0].CartFullCutList.length; i++) {
        for (var j = 0; j < cart.StoreCartList[0].CartFullCutList[i].FullCutCartProductList.length; j++) {
          cart.StoreCartList[0].CartFullCutList[i].FullCutCartProductList[j].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreCartList[0].CartFullCutList[i].FullCutCartProductList[j].OrderProductInfo.ShowImg;
        }
      }

    }
    return cart;

  },

  // 菜单列表
  menuList: function() {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/store/GetStoreClassList',
      data: {
        storeId: app.globalData.storeId
      },
      success: function(res) {
        var categories = [];
        for (var i = 0; i < res.data.Data.length; i++) {
          var temp = res.data.Data[i];
          if (temp.ParentId == 0) //只展示一级类目
          {
            var c = {};
            c.id = temp.StoreCid;
            c.name = temp.Name;
            c.productArr = []; //初始化二级商品
            categories.push(c);
          }
        }
        that.setData({
          categories: categories
        })
        that.searchGoods(categories)
      }
    });
  },

  searchGoods: function(categories) {
    var that = this,
      k = categories[0].k ? categories[0].k : 0
    wx.request({
      url: app.globalData.host + '/api/store/Search',
      data: {
        storeId: app.globalData.storeId,
        cateId: categories[k].id,
        word: '',
        page: 1,
        pageSize: 100, //每页加载总数
        priceStart: 0,
        priceEnd: 0
      },
      success: function(res) {
        if (res.data.Code == 0) {
          var productArr = []
          var allProductArr = []
          var skuArr = []
          var goodsResult = res.data.Data.ProductList
          if (goodsResult.length != 0) {
            goodsResult[0].title = categories[k].name
            goodsResult[0].menuId = categories[k].id
            for (var i = 0; i < goodsResult.length; i++) {
              goodsResult[i].ShowImg = app.globalData.image190_190host + goodsResult[i].ShowImg;
              goodsResult[i].RealCount = 0;
              goodsResult[i].SKUCount = 0;
              if (goodsResult[i].SKUGid == 0) {
                productArr.push(goodsResult[i]);
                allProductArr.push(goodsResult[i])
              } else if (goodsResult[i].SKUGid != 0) {
                skuArr.push(goodsResult[i])
                allProductArr.push(goodsResult[i])
                if (!that.checkProduct(productArr, goodsResult[i].SKUGid)) {
                  productArr.push(goodsResult[i]);
                }
              }
            }
          } else {
            var h = {}
            h.title = categories[k].name
            h.menuId = categories[k].id
            productArr.push(h)
          }
          var result = that.data.goodsResult
          productArr = result.concat(productArr);
          var skuArrResult = that.data.skuArr
          skuArr = skuArrResult.concat(skuArr);
          var allArrResult = that.data.allGoodsResult
          allProductArr = allArrResult.concat(allProductArr);
          that.setData({
            goodsResult: productArr,
            allGoodsResult: allProductArr,
            skuArr: skuArr
          });
        }
      },
      complete: function(res) {
        k++;
        if (k == categories.length) {
          console.log("执行完成")
        } else {
          categories[0].k = k;
          that.searchGoods(categories)
        }
      }
    })
  },
  //sku产品去重
  checkProduct: function(productList, text) {
    var state = false; //默认不存在
    if (productList.length > 0 & text != 0) {
      for (var i = 0; i < productList.length; i++) {
        if (text == productList[i].SKUGid) {
          state = true; //已经存在
          break;
        }
      }
    }
    return state;
  },

  //添加商品到购物车
  toShop: function() {
    if (this.data.selectProduct.length > 0) {
      wx.showLoading({
        title: '提交中',
      })
      var that = this;
      var selectProduct = that.data.selectProduct;
      var k = selectProduct[0].k ? selectProduct[0].k : 0
      wx.request({
        url: app.globalData.host + "/api/Cart/AddProduct?pid=" + selectProduct[k].pid + "&buyCount=1&uid=" + app.globalData.userInfo.Uid,
        success: function(res) {

        },
        complete: function(res) {
          var msg = []
          if (res.data.Code != 0) {
            msg.push(res.data.Message)
          }
          k++;
          if (k == selectProduct.length) {
            var productList = that.data.goodsResult
            for (var j = 0; j < productList.length; j++) { //商品
              if (productList[j].RealCount > 0) {
                productList[j].RealCount = 0
                that.setData({
                  'goodsResult': productList,
                  'total': {
                    RealCount: 0,
                    money: 0
                  }
                });
              }
            }
            that.setData({
              selectProduct: [],
              countPrice: 0
            })
            console.log("执行完成")
            wx.hideLoading()
            if (msg.length > 0) {
              wx.showToast({
                title: msg[0],
                icon: 'success',
                duration: 3000,
                complete: function() {
                  wx.reLaunch({
                    url: '/pages/shop-cart/index',
                  })
                }
              })
            } else {
              wx.reLaunch({
                url: '/pages/shop-cart/index',
              })
            }
          } else {
            selectProduct[0].k = k;
            that.toShop()
          }
        },
        fail: function(res) {
          wx.showToast({
            title: res.data.Message
          })
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: "请选择商品",
        showCancel: false
      })
      return;
    }
  },

  // 获取购物车数据
  reqShop: function() {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/cart/index',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: function(res) {
        if (res.data.Code == 0) {
          var cart = that.processImageHost(res.data.Data);
          that.setData({
            saveHidden: true,
            allSelect: true,
            noSelect: false,
            mallName: wx.getStorageSync('mallName'),
            cartInfo: cart
          });
        }
      }
    })
  },

  getFields: function(e) {
    let classes = {}
    classes["0"] = 0
    for (let i in this.data.categories) {
      var goodsResult = this.data.goodsResult
      for (var j = j ? j : 1; j < goodsResult.length; j++) {
        if (goodsResult[j].title) {
          classes[parseInt(i) + 1] = Math.ceil(j) * 85 + 23
          j++
          break;
        }
      }
    }
    for (let i in classes) {
      if (e.detail.scrollTop < classes[i]) {
        this.setData({
          selectedMenuId: i - 1,
          scrollTopId: "s" + (i - 1)
        })
        break;
      }
    }
  },
  selectMenu: function(event) {
    let data = event.currentTarget.dataset
    this.setData({
      toView: data.tag
    })
    var self = this;
    setTimeout(function() {
      self.setData({
        selectedMenuId: data.id
      });
    }, 100);
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    var that = this;
    let isAccredit = utils.isAccredit(function(isAccredit) {
      that.setData({
        isAccredit: isAccredit
      })
    });
    // 购物车商品
    // that.getShopCart();
    // if (app.globalData.diningSid == 0) {//非扫码点餐
    //   that.getShopCart();
    // }
    that.menuList();
  },
  getShopCart: function() {
    var that = this;
    // 获取购物车数据
    wx.request({
      url: app.globalData.host + '/api/cart/index',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: function(res) {
        let selectProduct = that.data.selectProduct;
        let total = that.data.total;
        if (res.data.Code == 0) {
          let shopList = res.data.Data.StoreCartList;
          if (shopList.length > 0) {
            let cartList = shopList[0].CartProductList;
            for (let i = 0; i < cartList.length; i++) {
              let pid = cartList[i].OrderProductInfo.Pid;
              let count = cartList[i].OrderProductInfo.RealCount;
              total.RealCount += cartList[i].OrderProductInfo.BuyCount;
              total.money += cartList[i].OrderProductInfo.BuyCount * cartList[i].OrderProductInfo.ShopPrice;
              let ShopPrice = cartList[i].OrderProductInfo.ShopPrice;
              selectProduct.push({
                pid: pid,
                count: count,
                total: total,
                ShopPrice: ShopPrice,
              })
            }
          }
          var countPrice = that.data.countPrice;
          var selectCount = that.data.selectCount;
          console.log(selectProduct);
          for (var i = 0; i < selectProduct.length; i++) {
            countPrice = countPrice + selectProduct[i].ShopPrice * selectProduct[i].count;
            selectCount = selectCount + selectProduct[i].count;
          }
          that.setData({
            total: total,
            countPrice: countPrice.toFixed(2),
            selectCount: selectCount,
            selectProduct: selectProduct
          });
        }
      }
    })
  },

  onReady: function() {
    // 页面渲染完成
  },
  onShow: function() {
    // 页面显示
    this.reqShop();
  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
})